package com.quanyan.ic.common.serialize;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by zhuo.shi on 2017/7/31.
 */
public class HessianSerializeUtils {

    public static byte[] serialize(Object obj) {
        if (obj == null) {
            throw new NullPointerException();
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            HessianOutput ho = new HessianOutput(os);
            ho.writeObject(obj);
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object deserialize(byte[] by) {
        if (by == null) {
            throw new NullPointerException();
        }
        try {
            ByteArrayInputStream is = new ByteArrayInputStream(by);
            HessianInput hi = new HessianInput(is);
            return hi.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T deserialize(byte[] by, Class<T> type) {
        if (by == null) {
            throw new NullPointerException();
        }
        try {
            ByteArrayInputStream is = new ByteArrayInputStream(by);
            HessianInput hi = new HessianInput(is);
            @SuppressWarnings("unchecked")
            T t = (T) hi.readObject(type);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
